//
//  ASDownLoadDetailVC.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/5/6.
//

#import "ASDownLoadDetailVC.h"
#import "GXCardView.h"
#import "ASDetailCardCell.h"
#import "ASDetailTopView.h"
#import "ASPhotoModel.h"
#import "ASNoneView.h"
#import "ASUserDetailMenuView.h"

@interface ASDownLoadDetailVC ()  <GXCardViewDataSource, GXCardViewDelegate>

@property (strong, nonatomic) NSMutableArray *dataSource;
@property (strong, nonatomic) NSArray *oldArr;
@property (assign, nonatomic) NSInteger showIndex;
@property (strong, nonatomic) GXCardView *cardView;
@property (strong, nonatomic) ASDetailTopView *topView;
@property (assign, nonatomic) ASDetailCardType cardType;            ///卡片类型
@property (strong, nonatomic) ASNoneView *noneView;
@property (strong, nonatomic) ASUserDetailMenuView *menuView;
@property (strong, nonatomic) ASPhotoModel *showModel;

@end

@implementation ASDownLoadDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"fafafa"];
    self.title = @"详情";
    self.cardType = ASDetailCardType_Square;
    [self.view addSubview:self.topView];
    [self.view addSubview:self.menuView];
    [self.view addSubview:self.cardView];
    [self.view addSubview:self.noneView];
    [ASTool addUMTongJiKey:@"details" subKey:@"portrail_detail" titleStr:@"总浏览量"];

    [self.cardView reloadData];
    [self createRightBtn];
    // Do any additional setup after loading the view.
}

- (ASDetailTopView *)topView{
    if (!_topView) {
        _topView = [[ASDetailTopView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 150)/2, Height_NavBar+15, 150, 40)];
        @weakify(self);
        _topView.clickSubBtnBlock = ^(NSInteger btnTag) {
            @strongify(self);
            self.cardType = btnTag;
            [ASTool addUMTongJiKey:@"details" subKey:@"portrail_detail" titleStr:btnTag>0?@"圆形":@"方形"];

            [self.cardView reloadDataFormIndex:self.showIndex];
        };
        if (self.type == 1) {
            _topView.hidden = YES;
        }
    }
    return _topView;
}

- (ASNoneView *)noneView{
    if (!_noneView) {
        _noneView = [[ASNoneView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT)];
        _noneView.backgroundColor = self.view.backgroundColor;
        [_noneView.logoImage setImage:[UIImage imageNamed:@"me_wsj"]];
        _noneView.titleLab.text = @"暂时没有更多数据了";
        _noneView.hidden = YES;
    }
    return _noneView;
}

- (GXCardView *)cardView{
    if (!_cardView) {
        _cardView = [[GXCardView alloc]initWithFrame:CGRectMake(40, self.topView.bottom+15, SCREEN_WIDTH - 80, SCREEN_WIDTH - 60)];
        _cardView.dataSource = self;
        _cardView.delegate = self;
        _cardView.visibleCount = 3;
        _cardView.lineSpacing = 15.0;
        _cardView.interitemSpacing = 10.0;
        _cardView.maxAngle = 15.0;
        _cardView.maxRemoveDistance = 100.0;
//        _cardView.isRepeat = YES;
    //    self.cardView.isRepeat = YES; // 新加入
        [_cardView registerClass:[ASDetailCardCell class] forCellReuseIdentifier:ASDetailCardCellStr];
    }
    return _cardView;
}

- (ASUserDetailMenuView *)menuView{
    if (!_menuView) {
        _menuView = [[ASUserDetailMenuView alloc]initWithFrame:CGRectMake(0, self.topView.bottom+15+(SCREEN_WIDTH - 60)+50, SCREEN_WIDTH, 90)];
        @weakify(self);
        _menuView.clickSubMenuBlock = ^(NSInteger index) {
            @strongify(self);
        };
        _menuView.hidden = YES;
    }
    return _menuView;
}

- (void)createRightBtn{
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [rightBtn setImage:[UIImage imageNamed:@"details_delete"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(clickDelteBtn) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
}

- (void)createOldArr:(NSArray *)oldArr showIndex:(NSInteger)showIndex{
    self.oldArr = oldArr;
    NSArray *firstArr = [oldArr subarrayWithRange:NSMakeRange(0, showIndex)];
    NSArray *lastArr = [oldArr subarrayWithRange:NSMakeRange(showIndex, oldArr.count-(showIndex))];
    self.dataSource = [NSMutableArray arrayWithArray:lastArr];
    [self.dataSource appendObjects:firstArr];
    FELog(@"asdfasdfadsf=====%@",self.dataSource);
}

#pragma mark - GXCardViewDataSource

-(NSInteger)numberOfCountInCardView:(GXCardView *)cardView{
    return self.dataSource.count;
}

- (GXCardViewCell *)cardView:(GXCardView *)cardView cellForRowAtIndex:(NSInteger)index{
    ASDetailCardCell *cell = [cardView dequeueReusableCellWithIdentifier:ASDetailCardCellStr];
    cell.type = self.cardType;
    if (self.dataSource.count > index) {
        ASPhotoModel *model = self.dataSource[index];
        if (model.showImage) {
            [cell.mainImage setImage:model.showImage];
        }else{
            [[PHImageManager defaultManager]requestImageDataForAsset:model.asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                UIImage * image = [UIImage imageWithData:imageData];
                model.showImage = image;
                [cell.mainImage setImage:image];
            }];
        }
    }
    return cell;
}

- (void)cardView:(GXCardView *)cardView didRemoveCell:(GXCardViewCell *)cell forRowAtIndex:(NSInteger)index direction:(GXCardCellSwipeDirection)direction{
//    FELog(@"adsasdfa===%zd",index);
    if (self.dataSource.count > index) {
        ASPhotoModel *model = self.dataSource[index];
        [self.dataSource addObject:model];
    }
}

- (void)cardView:(GXCardView *)cardView didDisplayCell:(GXCardViewCell *)cell forRowAtIndex:(NSInteger)index{
    FELog(@"adsasdfa===%zd",index);
    self.showIndex = index;
    if (self.dataSource.count > index) {
        self.showModel = self.dataSource[index];
    }
}

- (void)clickDelteBtn{
    if (self.dataSource.count > self.showIndex) {
        ASPhotoModel *model = self.dataSource[self.showIndex];
        [self clearPhotos:model.asset.localIdentifier deleteIndex:self.showIndex];
    }
}

/// 删除相册视频
- (void)clearPhotos:(NSString * )localIdentifier deleteIndex:(NSInteger)deleteIndex {
    ///配置获取相册视频操作相关参数
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]]; //yes为顺序，no为倒序
    options.includeAssetSourceTypes = PHAssetSourceTypeUserLibrary|PHAssetSourceTypeCloudShared|PHAssetSourceTypeiTunesSynced;
    options.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld",PHAssetMediaTypeImage];
    PHFetchResult *fetchRequest = [PHAsset fetchAssetsWithOptions:options];
    
    [MBProgressHUD showMessage:@"删除中..."];
    [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
        [fetchRequest enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            PHAsset *assetObj = obj;
            if ([assetObj.localIdentifier isEqualToString:localIdentifier]) {
                BOOL b = [assetObj canPerformEditOperation:PHAssetEditOperationDelete];
                if (b) {
                    [PHAssetChangeRequest deleteAssets:@[assetObj]];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUD];
                });
            }
        }];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.cardView removeTopCardViewFromSwipe:1];

                NSMutableArray *arr = [NSMutableArray arrayWithArray:self.dataSource];
                for (ASPhotoModel *model in arr) {
                    if ([model.asset.localIdentifier isEqualToString:localIdentifier]) {
                        [self.dataSource removeObject:model];
                    }
                }
                [self.cardView reloadData];
                if (self.dataSource.count < 1) {
                    self.noneView.hidden = NO;
                }
                [[NSNotificationCenter defaultCenter]postNotificationName:@"ReloadDownLoadData" object:nil];
                [MBProgressHUD hideHUD];
            });
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
